#!/usr/bin/env python
# -*- coding: utf-8 -*-

import rospy, sys
import moveit_commander
from control_msgs.msg import GripperCommand

class MoveItFkDemo:
    def __init__(self):
        # 初始化move_group的API
        moveit_commander.roscpp_initialize(sys.argv)
        # 初始化ROS节点
        rospy.init_node('moveit_fk_demo')
          # 初始化需要使用move group控制的机械臂中的arm group
        arm = moveit_commander.MoveGroupCommander('ls')
                
        # 获取终端link的名称
        end_effector_link = arm.get_end_effector_link()
                        
        # 设置目标位置所使用的参考坐标系
        reference_frame = 'base_link'
        arm.set_pose_reference_frame(reference_frame)
                
        # 当运动规划失败后，允许重新规划
        arm.allow_replanning(True)
        
        # 设置位置(单位：米)和姿态（单位：弧度）的允许误差
        arm.set_goal_position_tolerance(0.001)
        arm.set_goal_orientation_tolerance(0.001)
        
        target_pose = arm.get_current_pose()

        # 控制机械臂先回到初始化位置
        # arm.set_named_target('home')
        # arm.go()
        # rospy.sleep(2)
         
        # 设置夹爪的目标位置，并控制夹爪运动
        # gripper.set_joint_value_target([0.01])
        # gripper.go()
        # rospy.sleep(1)
        # target_pose = arm.get_current_pose()                
        # print(target_pose)      
        # 设置机械臂的目标位置，使用六轴的位置数据进行描述（单位：弧度）
        # joint_positions = [7.174386074766517e-05, 0.5897017249131575, 1.3311921344282571, 0.01689552930681966, 1.5671456990856676]

        # angle = 160
        # joint_positions = [0.5, angle/180.0*3.1415926, 0,(-angle + 90.0)/180.0*3.1415926,0]
        joint_positions = [0.7,2.177396204897007,0,-0.6066002048970067,0]

        arm.set_joint_value_target(joint_positions)
        rospy.sleep(2)
        target_pose = arm.get_current_pose()                
        print(target_pose)
        # 控制机械臂完成运动
        arm.go()
        rospy.sleep(1)
        
        # 关闭并退出moveit
        moveit_commander.roscpp_shutdown()
        moveit_commander.os._exit(0)

if __name__ == "__main__":
    try:
        MoveItFkDemo()
    except rospy.ROSInterruptException:
        pass
